var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// 添加请求日志中间件
app.use((req, res, next) => {
    console.log('请求信息:', {
        method: req.method,
        url: req.url,
        query: req.query,
        body: req.body
    });
    next();
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// 添加跨域支持
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
});

// 处理 OPTIONS 请求
app.options('*', (req, res) => {
    res.sendStatus(200);
});

app.use(logger('dev'));
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({ extended: false, limit: '50mb' }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 添加静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'public/uploads')));

// 修改重定向中间件
app.use('/users/*', (req, res, next) => {
    const newUrl = req.url.replace('/users', '/api/users');
    req.url = newUrl;
    next();
});

// 路由配置
app.use('/api', indexRouter);
app.use('/users', usersRouter);
app.use('/api/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    res.status(404).json({
        code: 404,
        msg: '接口不存在',
        data: null
    });
});

// error handler
app.use(function(err, req, res, next) {
    console.error('Error:', err);
    res.status(err.status || 500).json({
        code: err.status || 500,
        msg: err.message || '服务器错误',
        data: null
    });
});

// 引入数据库配置
const db = require('./config/db');

// 数据库连接测试
db.pool.query('SELECT 1')
    .then(() => {
        console.log('=================================');
        console.log('📦 数据库连接成功');
        console.log(`🗄️  数据库名称: ${process.env.DB_NAME}`);
        console.log(`🔌 数据库地址: ${process.env.DB_HOST}`);
        console.log('=================================');
    })
    .catch(err => {
        console.error('=================================');
        console.error('❌ 数据库连接失败');
        console.error(`🔥 错误信息: ${err.message}`);
        console.error('=================================');
    });

module.exports = app;
